<template>
  <div class="tag-list-container">
    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="标签名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入标签名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增标签
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column label="标签" min-width="200">
          <template #default="{ row }">
            <el-tag
              :color="row.color"
              :style="{ color: getTextColor(row.color) }"
              size="large"
              class="tag-display"
            >
              {{ row.name }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="颜色" width="120">
          <template #default="{ row }">
            <div class="color-display">
              <div
                class="color-block"
                :style="{ backgroundColor: row.color }"
              ></div>
              <span class="color-code">{{ row.color }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="使用次数" width="120">
          <template #default="{ row }">
            <el-tag type="info" size="small">
              {{ row.usageCount }} 次
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="180" />
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              :disabled="row.usageCount > 0"
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 标签表单弹窗 -->
    <tag-form
      v-model:visible="formVisible"
      v-model:tag-data="currentTag"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { getTagPage, deleteTag, TAG_COLORS } from '../../api/tag'
import TagForm from './components/TagForm.vue'

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 表单弹窗
const formVisible = ref(false)
const currentTag = ref(null)

// 计算文字颜色（根据背景色深浅）
const getTextColor = (backgroundColor) => {
  if (!backgroundColor) return '#333'
  
  // 去掉#号
  const hex = backgroundColor.replace('#', '')
  
  // 转换为RGB
  const r = parseInt(hex.substr(0, 2), 16)
  const g = parseInt(hex.substr(2, 2), 16)
  const b = parseInt(hex.substr(4, 2), 16)
  
  // 计算亮度
  const brightness = (r * 299 + g * 587 + b * 114) / 1000
  
  // 根据亮度返回黑色或白色文字
  return brightness > 128 ? '#333' : '#fff'
}

// 获取标签列表
const fetchTagList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await getTagPage(params)
    if (response.code === 200) {
      tableData.value = response.data.records
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    ElMessage.error('获取标签列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  fetchTagList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: ''
  })
  pagination.pageNum = 1
  fetchTagList()
}

// 新增标签
const handleAdd = () => {
  currentTag.value = null
  formVisible.value = true
}

// 编辑标签
const handleEdit = (row) => {
  currentTag.value = { ...row }
  formVisible.value = true
}

// 删除标签
const handleDelete = async (row) => {
  if (row.usageCount > 0) {
    ElMessage.warning('该标签正在被使用中，不能删除')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除标签 "${row.name}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteTag(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchTagList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除标签失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  fetchTagList()
}

// 页码改变
const handleCurrentChange = (page) => {
  pagination.pageNum = page
  fetchTagList()
}

// 表单提交成功
const handleFormSuccess = () => {
  fetchTagList()
}

// 页面加载时获取数据
onMounted(() => {
  fetchTagList()
})
</script>

<style scoped>
.tag-list-container {
  padding: 20px;
}

.search-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tag-display {
  font-weight: 600;
  border: none;
  font-size: 14px;
  padding: 8px 16px;
}

.color-display {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-block {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.color-code {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #666;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.el-button:disabled) {
  opacity: 0.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tag-list-container {
    padding: 15px;
  }
  
  .search-card {
    padding: 15px;
  }
  
  .table-card {
    padding: 15px;
  }
  
  :deep(.el-form--inline .el-form-item) {
    display: block;
    margin-bottom: 15px;
  }
  
  :deep(.el-form--inline .el-form-item__content) {
    margin-left: 0 !important;
  }
}
</style>
